<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 提示 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <!--        <el-step title="商品参数"></el-step>-->
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- Tab栏 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="activeIndex"
          :tab-position="'left'"
          :before-leave="beforeTabLeave"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="addForm.name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="price">
              <el-input v-model="addForm.price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="branch">
              <el-cascader
                v-model="classify"
                :options="classifySelect"
                :props="cascaderProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!--          <el-tab-pane label="商品参数" name="1">
                      &lt;!&ndash; 渲染表单的Item项 &ndash;&gt;
                      <el-form-item
                        v-for="item in manyTableData

                      "
                        :key="item.attr_id"
                        :label="item.attr_name"
                      >
                        &lt;!&ndash; 复选框组 &ndash;&gt;
                        <el-checkbox-group v-model="item.attr_vals">
                          <el-checkbox :label="cb" v-for="(cb, i) in item.attr_vals" :key="i" border></el-checkbox>
                        </el-checkbox-group>
                      </el-form-item>
                    </el-tab-pane>-->
          <el-tab-pane label="商品属性" name="1">
            <el-tag size="normal" type="success" v-for="(t,i) in addForm.tags" :key="i" style="margin: 15px">{{t}}
            </el-tag>
            <el-form-item label="商品标签">
              <el-input v-model="tag"></el-input>
            </el-form-item>
            <el-button type="primary" class="btnAdd" @click="addTag">添加</el-button>
            <el-button type="primary" class="el-icon-refresh" @click="clearTag">重置</el-button>

          </el-tab-pane>
          <el-tab-pane label="商品图片" name="2">
            <!-- action: 图片上传的API接口地址 -->
            <el-upload
              action="#"
              multiple
              :on-change="onchange"
              :on-preview="handlePreview"
              list-type="picture"
              :auto-upload="false"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="3">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addForm.details"></quill-editor>
            <!-- 添加商品 -->
            <el-button type="primary" class="btnAdd" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog title="图片预览" :visible.sync="previewDialogVisible" width="50%">
      <img :src="picPreviewPath" alt="" class="previewImg">
    </el-dialog>
  </div>
</template>

<script>
  import _ from 'lodash'

  export default {
    data() {
      return {
        //  商品标签
        tag: '',
        // 商品所属分类数组--index[0]:主分类,index[1]:次分类
        classify: [],
        // 步骤条默认激活 与左侧Tab联动
        activeIndex: '0',
        //商品图片
        photos: [],
        // 添加商品的表单对象
        addForm: {
          name: '',
          price: 0,

          // 图片的数组
          // pics: [],
          // 商品详情描述
          details: '',
          // attrs: []
          //  商品标签
          tags: [],
          //创建人
          creatBy: '',
          //二级分类
          branch: '',
          //主分类
          master: '',
        },
        addFormRules: {
          name: [
            {required: true, message: '请输入商品名称', trigger: 'blur'}
          ],
          price: [
            {required: true, message: '请输入商品价格', trigger: 'blur'}
          ],
          classify: [
            {required: true, message: '请选择商品分类', trigger: 'blur'}
          ]
        },
        // 商品分类下拉列表
        classifySelect: [],
        // 级联选择器配置
        cascaderProps: {
          expandTrigger: 'hover',
          label: 'label',
          value: 'value',
          children: 'children'
        },
        // 图片上传组件的请求对象
        /*      headerObj: {
                Authorization: window.sessionStorage.getItem('token')
              },*/
        picPreviewPath: '',
        // 图片预览对话框
        previewDialogVisible: false,
      }
    },
    created() {
      this.getCateList()
    },
    computed: {
      getCateId() {
        if (this.classify.length === 3) {
          return this.classify[2]
        }
        return null
      }
    },
    methods: {
      // 获取商品分类数据列表
      async getCateList() {
        const {data: res} = await this.$http.get('/commodityClassify/getCommodityBranchInfo')
        if (res.code !== "success") {
          return this.$message.error('获取商品分类失败！')
        }
        // 给数据列表赋值
        this.classifySelect = res.data['classifySelect'];

      },
      // 级联选择器选中项变化时出发
      handleChange() {
        //本项目商品分类只有两级
        if (this.classify.length !== 2) {
          this.classify = []
        } else {
          this.addForm.master = this.classify[0];
          this.addForm.branch = this.classify[1];
        }
      },
      beforeTabLeave(activeName, odlActiveName) {
        // 未选中商品分类阻止Tab标签跳转
        //本项目商品分类只有两级
        if (odlActiveName === '0' && this.classify.length !== 2) {
          this.$message.error('请先选择商品分类');
          return false
        }
        if (odlActiveName === '2' && this.photos.length === 0) {
          this.$message.error('请先选择商品图片');
          return false
        }
      },
      // 处理图片预览
      handlePreview(file) {
        this.picPreviewPath = file.response.data.url;
        this.previewDialogVisible = true
      },
      // 添加商品
      addGoods() {
        this.$refs.addFormRef.validate(async valid => {
          if (!valid) return this.$message.error('请填写必要的表单项！')
          // 发起请求添加商品
          var formData = new FormData();
          Object.keys(this.addForm).forEach(key => {
            formData.append(key, this.addForm[key])
          });
          this.photos.forEach(p => {
            formData.append('photos', p.raw);
          });

          const {data: res} = await this.$axios.post('commodity/saveNewCommodityInfo', formData);

          if (!res.result) return this.$message.error(res.message);
          this.$message.success(res.message);
          this.$router.push('/goods')
        })
      },
      onchange(file, fileList) {
        this.photos = fileList;
      },
      //添加标签
      addTag() {
        let flag = true;
        if (this.tag) {
          this.addForm.tags.forEach(e => {
            if (this.tag === e) {
              flag = false;
              this.$message.warning('标签' + this.tag + '已存在');
            }
          });
          if (flag) this.addForm.tags.push(this.tag);
        }
      },
      //重置标签
      clearTag() {
        this.addForm.tags = [];
        this.tag = '';
        this.$message.success('重置成功')
      }
    }
  }
</script>

<style lang='less' scoped>
  .el-checkbox {
    margin: 0 8px 0 0 !important;
  }

  .previewImg {
    width: 100%;
  }

  .btnAdd {
    margin-top: 15px
  }
</style>
